import axios from "axios";
import qs from "qs";
import { httpServer } from "./config";
import { urls } from "./urls";
let timeout = 50000;
axios.defaults.baseURL = "";
axios.defaults.withCredentials = false;
import router from "../router"


axios.interceptors.request.use(
    (config: any) => {
        let userInfo: any = sessionStorage.getItem('userInfo')
        userInfo = JSON.parse(userInfo);
        if (userInfo && userInfo.token) {
            config.headers['token'] = userInfo.token;
        }
        
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
// http response 拦截器
axios.interceptors.response.use(
    (response) => {

        return response;
    }, (error) => {
        let obj = JSON.parse(JSON.stringify(error));
        return Promise.reject(error);
    }
);



/**
 * 封装GetDownload请求
 * @param 请求地址
 * @param 请求参数
 * @returns {Promise}
 */
function GetDownload(url: any, data: any, type: any) {
    return new Promise((resolve, reject) => {
        axios({
            method: "GET",
            headers: { "content-type": "application/json" },
            url: `${httpServer}${urls[url]}?${type ? '' : qs.stringify(data)}`,
            data: type ? data : '',
            responseType: 'blob',
            timeout,
        }).then(
            (response: any) => {
                if (response.status === 200) {
                    if ("application/json" === response.headers["content-type"]) {
                        const fileReader: any = new FileReader()
                        fileReader.onloadend = () => {
                            const jsonData = JSON.parse(fileReader.result)
        
                        }
                        fileReader.readAsText(response.data)
                    } else {
                        let fileNames = ''
                        if (response.headers["content-disposition"]) {
                            let disposition = response.headers["content-disposition"]
                            let fileName = decodeURIComponent(disposition.substring(disposition.indexOf("=") + 1));
                            fileNames = fileName
                        }

                        let blob = new Blob([response.data], { type: "application/vnd.ms-excel" }); // 2.获取请求返回的response对象中的blob 设置文件类型，这里以excel为例
                        let url = window.URL.createObjectURL(blob); // 3.创建一个临时的url指向blob对象
                        // 4.创建url之后可以模拟对此文件对象的一系列操作，例如：预览、下载
                        let a = document.createElement("a");
                        // window.open(a.href, '_blank');
                        a.href = url;
                        a.download = fileNames;
                        if (fileNames) {
                        } else {
                            a.download = '下载文件';
                        }
                        a.click();
                        // 5.释放这个临时的对象url
                        window.URL.revokeObjectURL(url);
                    }
                }

                resolve(response.data);
                // } else {
                //     console.log('response', response);
                //     resolve(response.data);
                //     // sessionStorage.clear();
                //     // location.reload();
                // }
            },
            (err) => {
                reject(err);
            }
        );
    });
}

/**
 * 封装post请求
 * @param 请求地址
 * @param 请求参数
 * @returns {Promise}
 */
function Post(url: any, data: any,) {
    return new Promise((resolve, reject) => {
        axios({
            method: "POST",
            url: `${httpServer}${urls[url]}?${qs.stringify(data)}`,
            timeout,
        }).then(
            (response: any) => {
                // localStorage.setItem('token', response.headers.token)
                if (response.status === 200) {
                    resolve(response.data);
                } else {
                    sessionStorage.clear();
                    // location.reload();
                }
            },
            (err) => {
                console.log("系统异常，稍后再试", err);
                reject(err);
            }
        );
    });
}

/**
 * 封装post请求下载文件
 * @param 请求地址
 * @param 请求参数
 * @returns {Promise}
 */




function postDowlod(url: any, data: any,  ) {

    return new Promise((resolve, reject) => {
        axios({
            method: "POST",
            url: `${httpServer}${urls[url]}?${qs.stringify(data)}`,
            // data: type ? data : '',
            responseType: 'blob',
            timeout: timeout,
        }).then(
            (response) => {
                if (response.status === 200) {
                    if ("application/json" === response.headers["content-type"]) {
                        const fileReader: any = new FileReader()
                        fileReader.onloadend = () => {
                            const jsonData = JSON.parse(fileReader.result)
                            // Message({
                            //     message: jsonData.message,
                            //     type: 'error'
                            // })
                        }
                        fileReader.readAsText(response.data)
                    } else {

                        let fileNames = ''
                        if (response.headers["content-disposition"]) {
                            let disposition = response.headers["content-disposition"]
                            let fileName = decodeURIComponent(disposition.substring(disposition.indexOf("=") + 1));
                            fileNames = fileName
                        }

                        let blob = new Blob([response.data], { type: "application/vnd.ms-excel" }); // 2.获取请求返回的response对象中的blob 设置文件类型，这里以excel为例
                        let url = window.URL.createObjectURL(blob); // 3.创建一个临时的url指向blob对象
                        // 4.创建url之后可以模拟对此文件对象的一系列操作，例如：预览、下载
                        let a = document.createElement("a");
                        // window.open(this.GLOBAL.$WINDOWLINK + 'http://localhost:8080/ruralHighway/workbench', '_blank');
                        // window.open('http://localhost:8080/ruralHighway/workbench', '_blank');
                        a.href = url;
                        a.download = fileNames;
                        // if (fileNames) {
                        // } else {
                        //     a.download = '下载文件';
                        // }
                        a.click();
                        // 5.释放这个临时的对象url
                        window.URL.revokeObjectURL(url);
                        console.log('777777777777');
                        // }
                        
                    }

                    resolve(response.data);
                } else {
                    console.log('response', response);
                    // sessionStorage.clear();
                    // location.reload();
                }
            },
            (err) => {
                console.log("系统异常，稍后再试", err);
                reject(err);
            }
        );
    });
}

export {  Post,  postDowlod, GetDownload, };
